CSS Selector in Selenium
CSS Selector is one of the most powerful and commonly used locator strategies in Selenium WebDriver. It allows automation testers to identify web elements using CSS patterns based on attributes such as ID, class, name, type, value, relationships, and combinations of multiple attributes.
CSS Selectors are especially useful when an element does not have a unique ID or when a tester needs a concise and readable locator. Selenium WebDriver supports CSS selectors through the By.cssSelector() method.
CSS selectors are an important part of Selenium WebDriver element location. JustAcademy's Selenium training curriculum specifically includes locating elements using ID, XPath, and CSS selectors, along with WebDriver commands, forms, buttons, dropdowns, and web elements. You can explore the JustAcademy's Selenium Training Course and use the Register for Course Demo option for further learning information.
1. What is a CSS Selector?
A CSS Selector is a pattern used to select HTML elements based on their tag name, ID, class, attributes, relationships, or combinations of these properties.
In Selenium, a CSS Selector is passed to the By.cssSelector() method.
driver.findElement(By.cssSelector("selector"));
For example:
driver.findElement(By.cssSelector("#username"));
This statement locates an element whose HTML id attribute is username.
2. Why CSS Selectors are Important in Selenium
CSS Selectors provide a flexible way to locate web elements in automated tests. They are particularly useful when simple locators such as ID, Name, or Class Name are not sufficient.
- They can locate elements using IDs.
- They can locate elements using class names.
- They can locate elements using attributes.
- They can combine multiple attributes.
- They can identify child and descendant elements.
- They can identify elements using tag and class combinations.
- They can identify elements using attribute values.
- They are useful for dynamic web pages.
- They can create concise locators.
- They are useful alternatives to XPath in many scenarios.
3. Basic Syntax of CSS Selector in Selenium
The basic syntax is:
driver.findElement(By.cssSelector("CSS_SELECTOR"));
For example:
driver.findElement(By.cssSelector("#loginButton")).click();
4. Required Selenium Imports
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
5. Complete Basic Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CSSSelectorExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com");
driver.findElement(
By.cssSelector("#login")
).click();
driver.quit();
}
}
6. CSS Selector and HTML
Consider the following HTML:
<input id="username" type="text" name="username">
The ID-based CSS Selector is:
#username
Selenium code:
driver.findElement(
By.cssSelector("#username")
).sendKeys("admin");
7. CSS Selector Using ID
The hash symbol # is used to select an element by its ID.
<input id="email" type="email">
CSS Selector:
#email
Selenium:
driver.findElement(
By.cssSelector("#email")
).sendKeys("[email protected]");
8. CSS Selector Using Class
The dot . symbol is used to select an element by class.
<button class="login-button">Login</button>
CSS Selector:
.login-button
Selenium:
driver.findElement(
By.cssSelector(".login-button")
).click();
9. CSS Selector Using Tag Name
A CSS Selector can use an HTML tag directly.
<button>Login</button>
CSS Selector:
button
However, if many buttons exist on the page, the selector may not uniquely identify the desired button.
10. Tag and Class Combination
You can combine an HTML tag and class name.
<button class="submit-button">Submit</button>
CSS Selector:
button.submit-button
Selenium:
driver.findElement(
By.cssSelector("button.submit-button")
).click();
11. Tag and ID Combination
<input id="username" type="text">
CSS Selector:
input#username
Although #username is normally sufficient when the ID is unique, combining the tag and ID can make the selector more descriptive.
12. CSS Selector Using Name Attribute
CSS selectors can locate an element using the name attribute.
<input name="username" type="text">
CSS Selector:
input[name='username']
Selenium:
driver.findElement(
By.cssSelector("input[name='username']")
).sendKeys("admin");
13. CSS Selector Using Type Attribute
<input type="password">
CSS Selector:
input[type='password']
Selenium:
driver.findElement(
By.cssSelector("input[type='password']")
).sendKeys("secret123");
14. CSS Selector Using Value Attribute
<input type="submit" value="Login">
CSS Selector:
input[value='Login']
15. CSS Selector Using Placeholder
<input type="text" placeholder="Enter Username">
CSS Selector:
input[placeholder='Enter Username']
Selenium:
driver.findElement(
By.cssSelector("input[placeholder='Enter Username']")
).sendKeys("admin");
16. CSS Selector Using Multiple Attributes
Multiple attributes can be combined in a single CSS Selector.
<input type="text" name="username" placeholder="Enter Username">
CSS Selector:
input[type='text'][name='username']
Another example:
input[type='text'][name='username'][placeholder='Enter Username']
17. Why Use Multiple Attributes?
Multiple attributes make a selector more specific when a single attribute matches several elements.
input[name='username']
If multiple elements have the same name, a more specific selector can be used:
input[type='text'][name='username']
18. CSS Selector Using Class with Attribute
<input class="form-control" name="email" type="email">
CSS Selector:
input.form-control[name='email']
19. CSS Selector for Multiple Classes
Suppose an element contains multiple classes:
<button class="btn btn-primary submit">Submit</button>
CSS Selector:
button.btn.btn-primary.submit
Multiple class names are joined without spaces when they belong to the same element.
20. Important Difference Between Class and Descendant Selectors
Consider:
.container.button
This means an element having both container and button classes.
Whereas:
.container .button
means an element with class button located inside an element with class container.
21. CSS Selector for Child Elements
The > symbol selects a direct child.
<div class="login-form">
<input type="text">
</div>
CSS Selector:
div.login-form > input
22. CSS Selector for Descendant Elements
A space selects a descendant element at any level.
div.login-form input
This can locate an input inside the login form even if the input is nested deeper within the DOM.
23. Child Selector vs Descendant Selector
| Selector | Meaning |
> | Direct child |
| Space | Any descendant |
+ | Adjacent sibling |
~ | General sibling |
24. CSS Selector Using Descendant
<div class="login">
<div class="form-group">
<input name="username">
</div>
</div>
CSS Selector:
div.login input[name='username']
25. CSS Selector Using Direct Child
<div class="login">
<input name="username">
</div>
CSS Selector:
div.login > input[name='username']
26. CSS Selector Using Adjacent Sibling
The + selector identifies an element immediately following another element.
<label>Username</label>
<input type="text">
CSS Selector:
label + input
27. CSS Selector Using General Sibling
The ~ selector identifies matching sibling elements that appear after the specified element.
label ~ input
28. CSS Selector Using Attribute Presence
A CSS Selector can check whether an attribute exists.
<input type="text" required>
Selector:
input[required]
29. CSS Selector Using Attribute Equals
The = operator matches an exact attribute value.
input[type='text']
This selects input elements whose type attribute exactly equals text.
30. CSS Selector Using Attribute Starts With
The ^= operator matches an attribute value that starts with a specified string.
<input id="user_12345">
CSS Selector:
input[id^='user_']
31. CSS Selector Using Attribute Ends With
The $= operator matches an attribute value that ends with a specified string.
<input id="user_12345">
CSS Selector:
input[id$='12345']
32. CSS Selector Using Attribute Contains
The *= operator matches an attribute value containing a specified substring.
<input id="user_12345">
CSS Selector:
input[id*='user']
33. CSS Attribute Selector Operators
| Operator | Purpose | Example |
= | Exact match | input[name='email'] |
*= | Contains | input[id*='user'] |
^= | Starts with | input[id^='user_'] |
$= | Ends with | input[id$='_field'] |
~= | Contains a space-separated word | div[class~='active'] |
|= | Exact value or value followed by hyphen | div[lang|='en'] |
34. CSS Selector for Dynamic ID
Modern applications frequently generate dynamic IDs.
<input id="user_874923">
If the stable portion is user_, use:
input[id^='user_']
Another example:
input[id*='874']
35. CSS Selector for Dynamic Class
Suppose:
<button class="btn-submit-9384">Submit</button>
If the stable portion is btn-submit:
button[class*='btn-submit']
36. CSS Selector for Dynamic Name
<input name="username_123">
Selector:
input[name^='username_']
37. CSS Selector for Dynamic Attribute Values
Attribute matching is useful when only part of an attribute value is stable.
input[data-testid*='login']
This can match an element whose data-testid contains login.
38. CSS Selector Using Data Attributes
Modern web applications often use custom data attributes for automation.
<button data-testid="login-button">Login</button>
CSS Selector:
button[data-testid='login-button']
Selenium:
driver.findElement(
By.cssSelector("button[data-testid='login-button']")
).click();
39. CSS Selector Using aria-label
<button aria-label="Search">🔍</button>
CSS Selector:
button[aria-label='Search']
40. CSS Selector for Input Fields
<input type="text" name="username">
<input type="password" name="password">
Username:
input[name='username']
Password:
input[name='password']
41. CSS Selector for Buttons
<button id="loginBtn">Login</button>
Selector:
button#loginBtn
Or:
#loginBtn
42. CSS Selector for Links
<a href="/login">Login</a>
CSS Selector using tag and attribute:
a[href='/login']
43. CSS Selector for Links Using href
The href attribute can be used to identify links.
a[href='/courses']
For an external URL:
a[href='https://example.com']
44. CSS Selector for Checkbox
<input type="checkbox" name="terms">
CSS Selector:
input[type='checkbox'][name='terms']
Selenium:
driver.findElement(
By.cssSelector("input[type='checkbox'][name='terms']")
).click();
45. CSS Selector for Radio Button
<input type="radio" name="gender" value="male">
CSS Selector:
input[type='radio'][value='male']
46. CSS Selector for Dropdown
<select id="country">
<option value="india">India</option>
<option value="usa">USA</option>
</select>
CSS Selector:
select#country
47. CSS Selector for Dropdown Option
select#country option[value='india']
This selector identifies the India option inside the country dropdown.
48. CSS Selector for Images
<img src="/images/logo.png" alt="Company Logo">
CSS Selector:
img[alt='Company Logo']
49. CSS Selector for Tables
<table id="users">
<tr>
<td>John</td>
<td>[email protected]</td>
</tr>
</table>
Table selector:
table#users
50. CSS Selector for Table Rows
table#users tr
This selects rows inside the users table.
51. CSS Selector for Table Cells
table#users tr td
This selects cells inside rows of the users table.
52. CSS Selector for Specific Table Cell
CSS provides positional selectors that can be used for simple table structures.
table#users tr:nth-child(2) td:nth-child(1)
However, for complex data-driven table relationships, XPath or programmatic row processing may be easier to maintain.
53. CSS Selector with nth-child()
:nth-child() can select an element based on its position among siblings.
ul li:nth-child(2)
This selects the second list item.
54. CSS Selector with nth-of-type()
:nth-of-type() selects an element based on its position among elements of the same tag type.
div:nth-of-type(2)
55. CSS Selector with first-child
ul li:first-child
This selects the first li element that is the first child of its parent.
56. CSS Selector with last-child
ul li:last-child
This selects the last child matching the structure.
57. CSS Selector with first-of-type
div:first-of-type
58. CSS Selector with last-of-type
div:last-of-type
59. CSS Selector with not()
The :not() pseudo-class excludes matching elements.
input:not([type='hidden'])
This can select input elements whose type is not hidden.
60. CSS Selector with checked
The :checked pseudo-class can identify checked radio buttons and checkboxes.
input[type='checkbox']:checked
Radio button example:
input[type='radio']:checked
61. CSS Selector for Enabled Elements
The :enabled pseudo-class can identify enabled form controls.
input:enabled
62. CSS Selector for Disabled Elements
The :disabled pseudo-class can identify disabled controls.
input:disabled
63. CSS Selector for Required Fields
input:required
This can identify required input elements.
64. CSS Selector for Optional Fields
input:optional
65. CSS Selector Using Multiple Conditions
Multiple conditions can be combined without spaces when they refer to the same element.
input.form-control[type='text'][name='username']
66. CSS Selector Using Multiple Classes and Attributes
button.btn.primary[data-action='login']
This identifies a button that has the classes btn and primary and a matching data-action attribute.
67. CSS Selector with Comma
The comma allows multiple selectors to be grouped.
input[type='text'], input[type='email']
This matches both text and email input elements.
68. CSS Selector for Login Form
<form id="loginForm">
<input name="username" type="text">
<input name="password" type="password">
<button type="submit">Login</button>
</form>
Username:
form#loginForm input[name='username']
Password:
form#loginForm input[name='password']
Button:
form#loginForm button[type='submit']
69. Complete Login Automation Using CSS Selectors
driver.findElement(
By.cssSelector("input[name='username']")
).sendKeys("admin");
driver.findElement(
By.cssSelector("input[name='password']")
).sendKeys("admin123");
driver.findElement(
By.cssSelector("button[type='submit']")
).click();
70. CSS Selector for Registration Form
input[name='firstName']
input[name='lastName']
input[name='email']
input[name='password']
button[type='submit']
These selectors can be used to automate registration form fields.
71. CSS Selector for Search Box
<input id="search" type="search" placeholder="Search products">
Selector:
input#search
Or:
input[placeholder='Search products']
72. CSS Selector for Search Button
<button class="search-btn" type="submit">Search</button>
Selector:
button.search-btn
73. CSS Selector for E-Commerce Product Card
<div class="product-card" data-product-id="101">
<h3 class="product-name">Laptop</h3>
<button class="add-cart">Add to Cart</button>
</div>
Product card:
div.product-card[data-product-id='101']
Add to Cart button:
div.product-card[data-product-id='101'] button.add-cart
74. CSS Selector for Product Names
div.product-card .product-name
This selects product names within product cards.
75. CSS Selector for Navigation Menu
<nav class="main-menu">
<a href="/home">Home</a>
<a href="/courses">Courses</a>
<a href="/contact">Contact</a>
</nav>
All navigation links:
nav.main-menu a
Courses link:
nav.main-menu a[href='/courses']
76. CSS Selector for Footer
footer a
This identifies links inside the footer.
77. CSS Selector for Modal
<div class="modal" id="loginModal">
<input name="username">
</div>
Username inside modal:
div#loginModal input[name='username']
78. CSS Selector for Alert Messages
<div class="alert alert-success">Login successful</div>
Selector:
div.alert.alert-success
79. CSS Selector for Error Message
<div class="error-message">Invalid password</div>
Selector:
div.error-message
80. CSS Selector for Specific Form Section
<section id="billing">
<input name="city">
</section>
Selector:
section#billing input[name='city']
81. CSS Selector with WebDriver findElement()
The most common usage is:
WebElement element = driver.findElement(
By.cssSelector("#username")
);
Then an action can be performed:
element.sendKeys("admin");
82. CSS Selector with findElements()
findElements() returns a list of matching elements.
List<WebElement> buttons = driver.findElements(
By.cssSelector("button")
);
83. Count Elements Using CSS Selector
List<WebElement> links = driver.findElements(
By.cssSelector("nav a")
);
System.out.println(
"Number of links: " + links.size()
);
84. Loop Through CSS Selector Results
List<WebElement> links = driver.findElements(
By.cssSelector("nav a")
);
for (WebElement link : links) {
System.out.println(link.getText());
}
85. CSS Selector with Explicit Wait
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginButton = wait.until(
ExpectedConditions.elementToBeClickable(
By.cssSelector("button[type='submit']")
)
);
loginButton.click();
86. Required Imports for Explicit Wait
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
87. CSS Selector with Presence Wait
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(
By.cssSelector("#dashboard")
)
);
88. CSS Selector with Visibility Wait
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".dashboard")
)
);
89. CSS Selector with Clickable Wait
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(
By.cssSelector("button.login")
)
);
element.click();
90. CSS Selector and Implicit Wait
driver.manage().timeouts().implicitlyWait(
Duration.ofSeconds(10)
);
After configuring the implicit wait, CSS Selectors can be used normally with findElement().
91. CSS Selector and Dynamic Web Applications
Dynamic applications often generate changing IDs, classes, and other attributes. CSS attribute operators can help create selectors based on stable portions.
input[id^='user_']
button[class*='submit']
div[data-testid='login-panel']
92. CSS Selector for React Applications
React applications often generate dynamic class names. When available, stable attributes such as data-testid, aria-label, or stable IDs can provide clearer CSS Selectors.
button[data-testid='login-button']
93. CSS Selector for Angular Applications
Angular applications may contain framework-generated attributes and dynamic DOM structures. Prefer stable application-specific attributes where possible.
input[formcontrolname='username']
94. CSS Selector for Accessibility Attributes
button[aria-label='Close']
Accessibility attributes can sometimes provide stable and meaningful selectors when they are intentionally maintained by the application.
95. CSS Selector for FormControlName
<input formcontrolname="email" type="email">
Selector:
input[formcontrolname='email']
96. CSS Selector for Data-Test Attributes
<button data-test="submit-button">Submit</button>
Selector:
button[data-test='submit-button']
97. CSS Selector in Page Object Model
CSS Selectors are frequently stored as By objects in Page Object Model classes.
public class LoginPage {
private WebDriver driver;
private By username =
By.cssSelector("input[name='username']");
private By password =
By.cssSelector("input[name='password']");
private By loginButton =
By.cssSelector("button[type='submit']");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();
}
}
98. Reusable CSS Selector Utility
public WebElement findByCss(String selector) {
return driver.findElement(
By.cssSelector(selector)
);
}
Usage:
findByCss("#username").sendKeys("admin");
99. Reusable Click Method
public void clickByCss(String selector) {
driver.findElement(
By.cssSelector(selector)
).click();
}
Usage:
clickByCss("button.login");
100. Reusable Send Keys Method
public void typeByCss(String selector, String text) {
driver.findElement(
By.cssSelector(selector)
).sendKeys(text);
}
101. CSS Selector and Page Object Best Practice
Keep CSS Selectors centralized inside page classes instead of writing long selectors repeatedly throughout test methods.
private final By emailField =
By.cssSelector("input[name='email']");
102. CSS Selector and TestNG
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void verifyLoginButton() {
WebElement button = driver.findElement(
By.cssSelector("button[type='submit']")
);
Assert.assertTrue(button.isDisplayed());
}
103. CSS Selector for Test Validation
WebElement message = driver.findElement(
By.cssSelector(".success-message")
);
Assert.assertTrue(
message.isDisplayed()
);
104. CSS Selector for Error Validation
WebElement error = driver.findElement(
By.cssSelector(".error-message")
);
Assert.assertTrue(error.isDisplayed());
105. CSS Selector for Checked Checkbox
WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox']:checked")
);
This can be useful for verifying that at least one matching checkbox is currently checked.
106. CSS Selector for Selected Radio Button
WebElement radio = driver.findElement(
By.cssSelector("input[type='radio']:checked")
);
107. CSS Selector for Active Navigation Item
nav a.active
This selects a navigation link having the active class.
108. CSS Selector for Hidden Elements
CSS Selectors identify elements in the DOM but do not automatically make hidden elements interactable.
input[type='hidden']
If an element is hidden, Selenium interaction may require waiting for it to become visible or using an appropriate application-level interaction.
109. CSS Selector and ElementClickInterceptedException
If another element overlaps the target element, a click may result in ElementClickInterceptedException.
Possible solutions include:
- Wait for the blocking overlay to disappear.
- Wait until the target is clickable.
- Scroll the element into view when appropriate.
- Handle modal dialogs or popups.
110. CSS Selector and NoSuchElementException
If the selector does not match an element, Selenium can throw NoSuchElementException.
Check:
- Selector syntax.
- Attribute values.
- Current page.
- Iframe context.
- Dynamic loading.
- Whether the element actually exists.
111. CSS Selector and StaleElementReferenceException
If the DOM is refreshed or an element is replaced after it has been located, the previously stored WebElement can become stale.
In such situations, locate the element again.
112. CSS Selector and iframe
If the target element is inside an iframe, switch to that iframe before using the CSS Selector.
driver.switchTo().frame("loginFrame");
driver.findElement(
By.cssSelector("input[name='username']")
).sendKeys("admin");
driver.switchTo().defaultContent();
113. CSS Selector and Nested iframe
driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
driver.findElement(
By.cssSelector("#username")
).sendKeys("admin");
driver.switchTo().defaultContent();
114. CSS Selector and Shadow DOM
CSS Selectors can be used within an appropriate Shadow Root context, but Selenium must first access the shadow root. A normal document-level CSS search does not automatically cross a shadow DOM boundary.
115. CSS Selector vs ID Locator
| Feature | ID | CSS Selector |
| Syntax | By.id() | By.cssSelector() |
| Complexity | Simple | Flexible |
| Attribute matching | Limited to ID | Multiple attributes supported |
| Relationships | Not directly supported | Parent/child/sibling CSS patterns supported |
| Dynamic attributes | Limited | Attribute operators available |
116. CSS Selector vs Name Locator
| Feature | Name | CSS Selector |
| Method | By.name() | By.cssSelector() |
| Based on | name attribute | CSS pattern |
| Multiple conditions | Limited | Supported |
| Dynamic matching | Limited | Supported with attribute operators |
117. CSS Selector vs Class Name
| Feature | Class Name | CSS Selector |
| Method | By.className() | By.cssSelector() |
| Single class | Easy | Easy |
| Multiple classes | Limited | Supported |
| Attributes | No | Yes |
| Relationships | No | Yes |
118. CSS Selector vs XPath
| Feature | CSS Selector | XPath |
| Syntax | CSS-based | XPath-based |
| ID/Class | Excellent | Excellent |
| Attribute matching | Excellent | Excellent |
| Parent/child relationships | Supported | Supported |
| Text matching | Limited compared with XPath | Strong |
| Sibling relationships | Supported | Supported |
| Complex DOM navigation | Can be less expressive | Highly expressive |
| Readability | Often concise | Can become longer |
119. When to Prefer CSS Selector
- When an element has a stable ID or class.
- When attribute-based matching is sufficient.
- When a concise locator is preferred.
- When using combinations of classes and attributes.
- When identifying descendants or direct children.
- When dealing with dynamic attribute values using
*=, ^=, or $=.
120. When XPath May Be More Suitable
- When matching complex visible text is required.
- When advanced DOM relationships are needed.
- When CSS cannot express the required relationship conveniently.
- When an element needs to be located based on surrounding text or a related element.
121. Common CSS Selector Mistakes
- Using an incorrect ID.
- Using an incorrect class name.
- Forgetting the
# for an ID selector.
- Forgetting the
. for a class selector.
- Using a space when classes belong to the same element.
- Using a descendant selector when a direct-child selector was intended.
- Creating selectors that match multiple elements.
- Depending on dynamically generated class names.
- Ignoring iframe boundaries.
- Ignoring asynchronous page loading.
122. Common Mistake: Incorrect ID Syntax
HTML:
<input id="username">
Correct:
#username
Incorrect:
.username
123. Common Mistake: Incorrect Class Syntax
HTML:
<button class="login-button">Login</button>
Correct:
.login-button
Incorrect:
#login-button
124. Common Mistake: Space Between Classes
HTML:
<button class="btn primary">Submit</button>
To select the same element having both classes:
button.btn.primary
Using:
button.btn .primary
means an element with class primary inside an element with class btn, which is a different structure.
125. Common Mistake: Overly Long CSS Selectors
Avoid unnecessarily depending on the complete DOM hierarchy.
html body div.container div.row div.col-md-6 form div.form-group input.form-control
A shorter stable selector may be preferable:
input[name='username']
126. Common Mistake: Using Dynamic Classes
Some frameworks generate classes that may change between builds or sessions.
.css-1a2b3c4
If the class is not stable, prefer a stable application attribute such as:
[data-testid='username']
127. Best Practices for CSS Selectors
- Prefer stable and meaningful attributes.
- Use unique IDs when they are reliable.
- Use data-test or data-testid attributes when intentionally provided for automation.
- Avoid fragile selectors based on deep DOM hierarchy.
- Avoid randomly generated classes.
- Combine attributes when necessary for uniqueness.
- Use attribute operators for dynamic values.
- Use explicit waits for dynamically loaded elements.
- Keep selectors readable.
- Store selectors in Page Object classes.
- Validate selectors in browser Developer Tools.
128. CSS Selector Debugging in Browser Developer Tools
Modern browsers allow testers to inspect elements and test CSS selectors through Developer Tools.
A useful workflow is:
Open Web Page
↓
Right Click Element
↓
Select Inspect
↓
Identify HTML Element
↓
Find Stable ID/Class/Attribute
↓
Create CSS Selector
↓
Test Selector in Developer Tools
↓
Use Selector in Selenium
129. Testing CSS Selector in Console
Browser Developer Tools can be used to test a CSS Selector with document.querySelector().
document.querySelector("#username")
For multiple matching elements:
document.querySelectorAll("input")
This is useful for verifying whether a selector matches the intended element before using it in Selenium.
130. CSS Selector Interview Questions
Q1. What is a CSS Selector in Selenium?
A CSS Selector is a pattern used by Selenium WebDriver to identify web elements based on CSS-style rules such as ID, class, attributes, relationships, and positional selectors.
Q2. What method is used for CSS Selector?
By.cssSelector()
Q3. How do you locate an element by ID using CSS Selector?
driver.findElement(By.cssSelector("#username"));
Q4. How do you locate an element by class?
driver.findElement(By.cssSelector(".login-button"));
Q5. How do you locate an element using an attribute?
driver.findElement(
By.cssSelector("input[name='username']")
);
Q6. How do you match a partial attribute value?
input[id*='user']
Q7. What does ^= mean?
^= matches an attribute value that starts with a specified string.
Q8. What does $= mean?
$= matches an attribute value that ends with a specified string.
Q9. What does *= mean?
*= matches an attribute value that contains a specified string.
Q10. How do you select a direct child?
parent > child
Q11. How do you select a descendant?
parent child
Q12. How do you select a checked checkbox?
input[type='checkbox']:checked
Q13. Can CSS Selector be used with findElements()?
Yes.
driver.findElements(
By.cssSelector("button")
);
Q14. Can CSS Selectors handle dynamic IDs?
Yes, stable portions of dynamic attributes can be matched using CSS attribute operators.
input[id^='user_']
Q15. CSS Selector or XPath?
The choice depends on the DOM structure and the locator requirement. CSS Selectors are concise and powerful for attributes, classes, IDs, and CSS relationships, while XPath provides additional flexibility for text and more complex DOM navigation.
131. Practical Project: CSS Selector Based Login Automation
Consider a login page:
<form id="loginForm">
<input id="username" name="username" type="text">
<input id="password" name="password" type="password">
<button class="login-btn" type="submit">Login</button>
</form>
Automation:
driver.findElement(
By.cssSelector("#username")
).sendKeys("admin");
driver.findElement(
By.cssSelector("#password")
).sendKeys("admin123");
driver.findElement(
By.cssSelector("button.login-btn")
).click();
132. Practical Project: Registration Form Automation
driver.findElement(
By.cssSelector("input[name='firstName']")
).sendKeys("John");
driver.findElement(
By.cssSelector("input[name='lastName']")
).sendKeys("Smith");
driver.findElement(
By.cssSelector("input[type='email']")
).sendKeys("[email protected]");
driver.findElement(
By.cssSelector("input[type='password']")
).sendKeys("Password123");
driver.findElement(
By.cssSelector("button[type='submit']")
).click();
133. Practical Project: E-Commerce Automation
driver.findElement(
By.cssSelector("input[placeholder='Search products']")
).sendKeys("Laptop");
driver.findElement(
By.cssSelector("button.search-btn")
).click();
driver.findElement(
By.cssSelector("button.add-cart")
).click();
134. Practical Project: Navigation Automation
driver.findElement(
By.cssSelector("nav.main-menu a[href='/courses']")
).click();
135. Practical Project: Checkbox Validation
WebElement terms = driver.findElement(
By.cssSelector("input[type='checkbox'][name='terms']")
);
if (!terms.isSelected()) {
terms.click();
}
136. Practical Project: Radio Button Validation
WebElement male = driver.findElement(
By.cssSelector("input[type='radio'][value='male']")
);
if (!male.isSelected()) {
male.click();
}
137. Practical Project: Verify Selected Radio Button
WebElement selected = driver.findElement(
By.cssSelector("input[type='radio']:checked")
);
System.out.println(
"Selected value: " +
selected.getAttribute("value")
);
138. Practical Project: Table Automation
List<WebElement> rows = driver.findElements(
By.cssSelector("table#users tbody tr")
);
for (WebElement row : rows) {
System.out.println(row.getText());
}
139. Practical Project: Dynamic Product Cards
List<WebElement> products = driver.findElements(
By.cssSelector("div.product-card")
);
for (WebElement product : products) {
System.out.println(product.getText());
}
140. CSS Selector Automation Flow
Launch Browser
↓
Open Application
↓
Inspect DOM
↓
Identify Stable Attribute
↓
Create CSS Selector
↓
Validate Selector
↓
Use By.cssSelector()
↓
Locate WebElement
↓
Perform Action
↓
Validate Result
↓
Continue Test
↓
Close Browser
141. CSS Selector Quick Reference
| Requirement | CSS Selector |
| ID | #username |
| Class | .login-button |
| Tag | input |
| Tag + Class | button.login-button |
| Tag + ID | input#username |
| Name | input[name='username'] |
| Type | input[type='password'] |
| Exact Attribute | input[name='email'] |
| Contains Attribute | input[id*='user'] |
| Starts With | input[id^='user_'] |
| Ends With | input[id$='_field'] |
| Direct Child | form > input |
| Descendant | form input |
| Adjacent Sibling | label + input |
| General Sibling | label ~ input |
| First Child | li:first-child |
| Last Child | li:last-child |
| Checked | input:checked |
| Disabled | input:disabled |
| Enabled | input:enabled |
| Not | input:not([type='hidden']) |
142. CSS Selector Best-Practice Checklist
- Use stable IDs whenever appropriate.
- Use stable class names rather than generated classes.
- Prefer dedicated test attributes such as
data-testid when available.
- Use multiple attributes when one attribute is not unique.
- Use
^=, *=, and $= for stable portions of dynamic attributes.
- Avoid unnecessarily long DOM paths.
- Avoid selectors that depend on fragile page structure.
- Check whether the selector matches exactly the intended element.
- Use explicit waits for dynamic elements.
- Use Page Object Model for reusable selectors.
- Use CSS Selector or XPath according to the actual locator requirement.
143. Final Conclusion
CSS Selector is a powerful Selenium locator strategy that allows testers to identify web elements using IDs, classes, tags, attributes, attribute patterns, child relationships, sibling relationships, and pseudo-classes. The basic Selenium syntax is By.cssSelector().
A good CSS Selector should be unique, stable, readable, maintainable, and resistant to unnecessary UI changes. Simple selectors such as IDs and classes are useful when stable, while attribute operators and structural selectors are helpful for dynamic applications.
CSS Selectors are particularly valuable for Selenium automation involving login forms, registration forms, navigation menus, buttons, checkboxes, radio buttons, dropdowns, tables, e-commerce applications, dashboards, and dynamic web applications.
For structured Selenium learning covering WebDriver, locators, CSS selectors, XPath, web elements, forms, TestNG, Page Object Model, dynamic elements, and practical automation projects, explore the JustAcademy's Selenium Training Course.
For additional information and course demonstration options, visit the Register for Course Demo page.